import React, {useEffect, useState, useRef} from 'react';
import { Card, Col, Row, List, Avatar, Drawer  } from 'antd';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import * as echarts from 'echarts'
import axios from 'axios';
import _ from 'lodash'

const { Meta } = Card;
const Home = () => {
    const { username, region, role:{roleName} } = JSON.parse(localStorage.getItem("token"))
    const [viewState, setviewState] = useState([])
    const [starState, setstarState] = useState([])
    const [visible, setVisible] = useState(false)
    const [peiChart, setpeiChart] = useState(null)
    const [allList, setallList] = useState([])
    const barRef = useRef()
    const pieRef = useRef()

    //天气demo
    useEffect(()=>{
        axios.get(`/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6`).then(res=>{
            setviewState(res.data)
        })
    },[])
    useEffect(()=>{
        axios.get(`/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6`).then(res=>{
            setstarState(res.data)
        })
        return () => {
            window.onresize = null
        }
    },[])
    //渲染柱状图的方法
    useEffect(()=>{
        // 请求数据
        axios.get(`/news?publishState=2&_expand=category`).then(res=>{
            // lodash
            const groupBy = _.groupBy(res.data, item=>item.category.title)
            renderBarView(groupBy)
            setallList(res.data)
        })
    },[])
    // 柱状图函数
    const renderBarView = (obj) => {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(barRef.current);
        // 指定图表的配置项和数据
        var option = {
                title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量'],
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel: {
                    interval: 0
                }
            },
            yAxis: {
                minInterval: 1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map(item=>item.length)
                },
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        // 表格自适应
        window.onresize= () => {
            myChart.resize()
        }
    }
    // 渲染个人饼状图的方法
    const renderPieView = (obj) => {
        //处理数据过滤出属于自家的数据
        var currentList = allList.filter(item=>item.author === username)
        const groupBy = _.groupBy(currentList, item=>item.category.title)
        console.log(groupBy)
        var list = []
        for(var i in groupBy){
            list.push({
                name: i,
                value: groupBy[i].length
            })
        }
        console.log(list)

        var myChart;
        if (!peiChart) {
            myChart = echarts.init(pieRef.current);
            setpeiChart(myChart)
        }else{
            myChart = peiChart
        }
        var option;
        option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '1%',
            left: 'center'
        },
        series: [
            {
            name: '当前用户新闻分类',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: list
            }
        ]
        };

        option && myChart.setOption(option);
    }
    return (
        <div className="site-card-wrapper">
            <Row gutter={16}>
                <Col span={8}>
                    <Card title="用户最常浏览" bordered={true}>
                    <List
                    size="large"
                    dataSource={viewState}
                    renderItem={item => 
                    <List.Item>
                        <a href={`#/news-manage/preview/${item.id}`}>
                            {item.title}
                        </a>
                    </List.Item>}
                    />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card title="用户点赞最多" bordered={true}>
                    <List
                    size="large"
                    dataSource={starState}
                    renderItem={item => 
                        <List.Item>
                            <a href={`#/news-manage/preview/${item.id}`}>
                                {item.title}
                            </a>
                        </List.Item>}
                    />
                    </Card>
                </Col>
                <Col span={8}>
                <Card
                    style={{ width: 300 }}
                    cover={
                    <img
                        alt="example"
                        src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                    />
                    }
                    actions={[
                    <SettingOutlined key="setting" onClick={()=>{
                        setTimeout(() => {
                            setVisible(true)
                            renderPieView()
                        }, 0);
                    }}/>,
                    <EditOutlined key="edit" />,
                    <EllipsisOutlined key="ellipsis" />,
                    ]}
                >
                    <Meta
                    avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                    title={username}
                    description={<div>
                        <b>{region?region:"全球"}</b>
                        <b style={{marginLeft:"20px"}}>{roleName}</b>
                    </div>}
                    />
                </Card>
                </Col>
            </Row>
            <div ref={barRef} style={{width:"100%", height:"400px"}}></div>
            <Drawer title="当前用户新闻信息" placement="right" width="30%" onClose={()=>setVisible(false)} visible={visible}>
                <div ref={pieRef} style={{width:"80%", height:"400px", marginLeft: "0%"}}></div>
            </Drawer>
        </div>
    );
};

export default Home;